import R from '@common/type/response';
import type { NextApiResponse } from 'next';
import * as userService from '@/common/service/sys_user';
import { AuthenticatedRequest, withAuth } from '@common/middleware/auth';
import { SysUserRoleService } from '@common/service/sys_user_role';

export async function handler(req: AuthenticatedRequest, res: NextApiResponse) {
  const { id } = req.query;
  if (!id) {
    res.status(400).json({ success: false, message: '缺少用户ID' });
    return;
  }
  if (req.method === 'GET') {
    // 获取单个用户
    const data = await userService.getUserById(Number(id)) as any;
    const role_ids = await SysUserRoleService.getUserRoleIds(Number(id))
    data.role_ids = role_ids
    // 删除密码
    delete data.password;
    R.success(res, data);
  } else if (req.method === 'PUT' || req.method === 'PATCH') {
    // 更新用户
    const affected = await userService.updateUser(Number(id), req.body);
    R.success(res);
  } else if (req.method === 'DELETE') {
    // 删除用户
    const affected = await userService.deleteUser(Number(id));
    R.success(res)
  } else {
    R.errWithStatus(res,405,'Method Not Allowed');
  }
}

export default withAuth(handler,{
  GET:'system:user:query',
  PUT:'system:user:update',
  DELETE:'system:user:remove'
}); 